﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.Text;
using System.Data;
using App.Core.DB;

public partial class Pages_Public_ProjectList : BasePage
{
    private int _PropertyTypeID = 0;
    private double _SizeFrom = 0;
    private double _SizeTo = 0;
    private int _CustomerID = 0;
    private int _CityID = 0;
    private int _StatusID = 0;
    private int _ZoneID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            SearchProjects(1);
        }
    }
    protected void BindPageInfo()
    {
        _CustomerID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.CUSTOMER_ID);
        _SizeFrom = WebUtil.GetQueryStringInDouble(AppConstants.QueryString.SIZE_FROM);
        _SizeTo = WebUtil.GetQueryStringInDouble(AppConstants.QueryString.SIZE_TO);
        _PropertyTypeID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.PROPERTY_TYPE_ID);
        _CityID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.CITY_ID);
        _StatusID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.STATUS_ID);
        _ZoneID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ZONE_ID);
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
    protected void SearchProjects(int pageNumber)
    {        
        UtilityDAO dao = new UtilityDAO();
        int totalRecord = 0;
        DataSet ds = dao.SerchProject(_CustomerID, _PropertyTypeID, _SizeFrom, _SizeTo, _StatusID, _CityID, _ZoneID, ConfigReader.BrocheureFileTypeID, pageNumber, ConfigReader.ProjectListSize, out totalRecord);
        DataTable dt = ds.Tables[0];
        BtcHousingEntities context = new BtcHousingEntities();
        BindCompanyInfo(context);
        //if (_PropertyTypeID > 0)
        //{            
        //    var propertyType = context.PropertyTypes.FirstOrDefault(P => P.ID == _PropertyTypeID);
        //    if (propertyType != null)
        //        h4Heading.InnerHtml = String.Format("Project List of {0}", propertyType.Name.HtmlEncode());
        //}
        if (dt.Rows.Count > 0)
        {
            String listItemHtml = @"<div class='ListItem'>   
                                        <table cellpadding='0' cellspacing='0'>
                                            <tr>
                                                <td>                                 
                                                    <div class='ListTitle'><a href='/Pages/Public/ProjectDetails.aspx?ID={0}' target='_blank'>{1}</a></div>
                                                    <div class='ListSubTitle'><b>Location:</b> {2} <b>Price Per {3}:</b> {4}</div>
                                                    <div style='margin-top:5px;'>
                                                        {6}
                                                        <div class='ListBotter'><b>Developer: </b><span>{7}</span></div>                
                                                    </div>
                                                </td>
                                                <td style='width:60px;'>
                                                    {5}
                                                </td>
                                             </tr>               
                                        </table>                                    
                                    </div>
                                    <div class='ListSeparator'><div></div></div>";
            
            StringBuilder sb = new StringBuilder(10);
            String thumbImage = "<img src='" + AppConstants.PROJECT_FILES + "/{0}/{1}' alt='' title='' align='right' class='ThumbInList' />";
            foreach (DataRow row in dt.Rows)
            {
                String priceHtml = String.Empty;                
                Project proj = new Project();
                //proj.PricePerUnitFrom
                decimal pricePerUnitFrom = NullHandler.GetDecimal(row["PricePerUnitFrom"]);
                decimal pricePerUnitTo = NullHandler.GetDecimal(row["PricePerUnitTo"]);
                int projectID = NullHandler.GetInt(row["ID"]);
                if (pricePerUnitFrom > 0 && pricePerUnitTo > 0 & NullHandler.GetBoolean(row["ShowPricingInfo"]))
                    priceHtml = String.Format("From {0} To {1}", WebUtil.FormatData(pricePerUnitFrom), WebUtil.FormatData(pricePerUnitTo));
                else
                    priceHtml = " Contact Us";//"Negotiatable";

                String thumnail = NullHandler.GetString(row["ProjectImage"]);
                if (!thumnail.IsNullOrEmpty())
                    thumnail = String.Format(thumbImage, projectID, thumnail);

                sb.AppendFormat(listItemHtml, projectID
                    , NullHandler.GetString(row["ProjectName"]).HtmlEncode()
                    , String.Format("{0}, {1}", NullHandler.GetString(row["City"]),  NullHandler.GetString(row["Zone"]))
                    , NullHandler.GetString(row["UnitName"]), priceHtml
                    , thumnail, GetDisplayableProjectDescription(NullHandler.GetString(row["Description"]), projectID)
                    , NullHandler.GetString(row["Company"]).HtmlEncode());
            }
            ltrListing.Text = sb.ToString();

            ///Bind Pager Controls
            ucPagerBottom.TotalRecord = totalRecord;
            ucPagerBottom.TotalRecordMessage = "Total {0} Project(s) Found.";
            ucPagerBottom.PageSize = ConfigReader.ProjectListSize;
            ucPagerBottom.PageNo = pageNumber;
            ucPagerBottom.DataBind();
        }
        else
            WebUtil.ShowMessageBox(divMessage, "Sorry! No project found.", false);
    }

    protected void BindCompanyInfo(BtcHousingEntities context)
    {
        if (_CustomerID > 0)
        {
            var customer = context.Customers.FirstOrDefault(C => C.ID == _CustomerID);
            if (customer != null)
            {                
                ltrHeadingCompanyName.Text = customer.Name;
                if (!customer.Logo.IsNullOrEmpty())
                {
                    imgCompanyLogo.ImageUrl = String.Format("{0}/{1}", AppConstants.CUSTOMER_LOGO, customer.Logo);
                    imgCompanyLogo.ToolTip = imgCompanyLogo.AlternateText = String.Format("{0} Logo", customer.Name.HtmlEncode());
                    imgCompanyLogo.Visible = true;
                }                                
                ///Bind Addresses
                var addresses = from P in context.Addresses where P.CustomerID == _CustomerID select P;
                if (addresses != null && addresses.Count() > 0)
                {
                    List<Address> addressList = addresses.ToList();
                    if (addressList.Count == 1)
                    {
                        BindCompanyAddress(addressList[0]);
                        //chkIsBillingAddress.Checked = true;
                    }
                    else
                    {
                        Address companyAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == false);
                        BindCompanyAddress(companyAddress);
                        //Address billingAddress = addressList.FirstOrDefault(A => A.IsBillingAddress == true);
                        //BindBillingAddress(billingAddress);
                    }
                }
                divCompanyInfo.Visible = true;
            }
        }
    }

    protected void BindCompanyAddress(Address companyAddress)
    {
        String country = companyAddress.City.Country.Name;
        String city = companyAddress.City.Name;
        StringBuilder streeAddress = new StringBuilder(companyAddress.StreetAddress.HtmlEncode());
        if (streeAddress.Length > 0 && !companyAddress.ZipCode.IsNullOrEmpty())
            streeAddress.Append(", ");
        streeAddress.Append(companyAddress.ZipCode.HtmlEncode());
        if (streeAddress.Length > 0)
            streeAddress.Append("<br />");

        //spanLocation.InnerHtml = String.Format("<br />{0}{1}, {2}", streeAddress.ToString(), city, country);
        ltrLocation.Text = String.Format("{0}{1}, {2}", streeAddress.ToString(), city, country);        
    }


    /// <summary>
    /// Old Implementation
    /// </summary>
//    protected void SearchProjects()
//    {
//        BtcHousingEntities context = new BtcHousingEntities();
//        var projects = from P in context.Projects where P.IsDeleted == false select P;
//        if (_PropertyTypeID > 0)
//        {
//            projects = from P in context.Projects where P.PropertyTypeID == _PropertyTypeID && P.IsDeleted == false select P;
//            var propertyType = context.PropertyTypes.FirstOrDefault(P => P.ID == _PropertyTypeID);
//            if (propertyType != null)
//                h4Heading.InnerHtml = String.Format("Project List of {0}", propertyType.Name.HtmlEncode());
//        }
//        String listItemHtml = @"<div class='ListItem'>                                    
//                                    <div class='ListTitle'><a href='/Pages/Public/ProjectDetails.aspx?ID={0}'>{1}</a></div>
//                                    <div class='ListSubTitle'><b>Location:</b> {2} <b>Price Per {3}:</b> {4}</div>
//                                    <div style='margin-top:5px;'>
//                                        {5}{6}
//                                        <div class='ListBotter'><b>Developer: </b><span>{7}</span></div>                
//                                    </div>                                    
//                                </div>";
//        String thumbImage = "<img src='" + AppConstants.PROJECT_FILES + "/{0}/{1}' alt='' title='' align='right' class='ThumbInList' />";
//        StringBuilder sb = new StringBuilder(10);
//        foreach (Project project in projects)
//        {
//            String priceHtml = String.Empty;
//            String thumnail = String.Empty;
//            if (project.PricePerUnitFrom > 0 && project.PricePerUnitTo > 0 & project.ShowPricingInfo)
//                priceHtml = String.Format("From {0} To {1}", WebUtil.FormatData(project.PricePerUnitFrom), WebUtil.FormatData(project.PricePerUnitTo));
//            else
//                priceHtml = "Negotiatable";
            
//            ProjectFile projectFile = project.ProjectFiles.FirstOrDefault(P => P.FileTypeID != ConfigReader.ProjectBrocheureFileTypeID);
//            if (projectFile != null && !projectFile.ThumbFileName.IsNullOrEmpty())             
//                thumnail = String.Format(thumbImage, project.ID, projectFile.ThumbFileName);

//            sb.AppendFormat(listItemHtml, project.ID, project.Name.HtmlEncode(),
//                String.Format("{0}, {1}", project.Zone.City.Name, project.Zone.Name),
//                project.Unit.Name, priceHtml,
//                thumnail, GetDisplayableProjectDescription(project),
//                project.Customer.Name.HtmlEncode());                
//        }
//        ltrListing.Text = sb.ToString();
//    }

    protected String GetDisplayableProjectDescription(String text, int projectID)
    {
        //TODO: Client Does Not Want this 
        //if (text.WordCount() > ConfigReader.ProjectListDescriptionWordCount)
        //    return String.Format("{0} &nbsp;&nbsp;<a href='/Pages/Public/ProjectDetails.aspx?ID={1}'>Details</a>", WebUtil.FormatText(text.GetWords(ConfigReader.ProjectListDescriptionWordCount)), projectID);

        //return WebUtil.FormatText(text);

        return String.Empty;
    }

    protected void ucPagerBottom_PageIndexChanged(object sender, PagerEventArgs e)
    {
        SearchProjects(e.PageIndex);
    }
}